<?php

namespace App\Http\Controllers\Admin;

use App\Extend\Qniu;
use App\Extend\Token;
use App\Extend\Predis;
use App\Rules\AdminRule;
use App\Service\RoleService;
use Illuminate\Http\Request;
use App\Service\AdminService;
use Illuminate\Http\JsonResponse;

/**
 * 个人中心（登录、退出、token相关）.
 */
class SsoController extends BaseController
{
    public function __construct(Request $request)
    {
        // 获取当前路由指向的方法名
        $routeAction = $request->route()->getActionMethod();
        //登录操作时，无需解析token获取用户信息
        if ('login' == $routeAction) {
            return;
        }
        parent::__construct($request);
    }

    /**
     * 登录.
     *
     * @param Request $request
     */
    public function login(Request $request)
    {
        $username = $request->input('username');
        $password = $request->input('password');

        // 验证参数
        $adminRule = new AdminRule();
        if (!$adminRule->scene('login')->check(['username' => $username, 'password' => $password])) {
            return failJson($adminRule->getError());
        }

        // 验证是否可以登录
        $info = AdminService::loginCheck($username, $password);

        // 更新登录信息
        $info['ip'] = $request->getClientIp();
        AdminService::saveLoginInfo($info);

        // 生成token(注意：前端给的token为 token+)
        $token = Token::getToken(['id' => $info['id'], 'username' => $info['username'], 'time' => time()]);

        //组成完成的token信息
        $data['token']     = $token;
        $data['timestamp'] = time();
        $data['sign']      = md5(config('style.app.secret') . $data['timestamp'] . $data['token']);

        return successJson(['username' => $info['username'], 'token' => $token, 'full_token' => base64_encode(json_encode($data))]);
    }

    /**
     * 退出登录.
     *
     * @return JsonResponse
     */
    public function logout()
    {
        return successJson();
    }

    /**
     * 修改密码
     */
    public function changePassword()
    {
        $data['password']         = $this->requestArr['password'];
        $data['old_password']     = $this->requestArr['old_password'];
        $data['confirm_password'] = $this->requestArr['confirm_password'];

        // 验证参数
        $adminRule = new AdminRule();
        if (!$adminRule->scene('change_password')->check($data)) {
            return failJson($adminRule->getError());
        }

        $id     = $this->userId;
        $result = AdminService::changePassword($id, $data['old_password'], $data['password']);

        return successJson($result);
    }

    /**
     * 获取权限.
     */
    public function getPermission()
    {
        $permission = RoleService::getPermission($this->roleId, $this->isAdmin);

        return successJson($permission);
    }

    /**
     * 获取七牛云token
     * vue直接上传文件至七牛云使用.
     */
    public function getQiniuToken()
    {
        $token = Qniu::getToken();

        $data = ['uptoken' => $token];

        return json_encode($data);
    }
}
